#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <pthread.h>
#include <math.h>
#include <string.h>
#include "ultrasonic.h"
#include "rgb.h"
#include "steer.h"
#include "motor.h"

//按键次数监测
int key1 = 0;//步进电机
int key3 = 0;//舵机
int steer_statu;//舵机状态：1表示开，0表示关
int motor_statu;//步进电机状态：1表示开，0表示关
pthread_t pt_key;
int temp_light_val = 0;//接收get_temper_light的返回值
int distance = 0;//接收超声波测距返回值
int light_value = 0;
int temp_value = 0;

//超声波相关变量的定义
struct gpio_desc gpio_val[6];
struct gpio_desc gpios;
char gpio_num[6];//管脚编号
char pptr[128];
char buff4_4[BUFFSIZE];
char buff4_5[BUFFSIZE];
//int trash_distance = 0;//接收超声波测距的返回值

//PWM_RGB相关变量的定义
unsigned long duty1 = 0;//0
unsigned long duty2 = 1000000;//1000000
unsigned long duty = 0;//0
int increase = 1;
int step;//1000;
char dutys[256];
char pwm0_path[128];
char pwm2_path[128];

//舵机相关变量的定义
int uart_fd;
char buf_steer[8];

//步进电机相关变量定义
char buff4_1[BUFFSIZE];
char buff4_3[BUFFSIZE];
char buff4_11[BUFFSIZE];
char buff5_12[BUFFSIZE];
char buff5_13[BUFFSIZE];
char buff5_14[BUFFSIZE];

//线程函数
void *key_func ()
{
	struct pollfd fds4_1[1];
	struct pollfd fds4_3[1];
	int gpio_value_fd4_1, gpio_value_fd4_3;
	int ret = 0;

	//设置key1、key2监听
	//当key2中断发生时, 唤醒poll进程读取value的值
	gpio_value_fd4_1 = open (buff4_1, O_RDONLY);
	if (gpio_value_fd4_1 == -1) {
		perror ("open value_key1 file error");
		exit (-1);
	}
	fds4_1[0].fd = gpio_value_fd4_1;
	fds4_1[0].events = POLLPRI;
	ret = read (gpio_value_fd4_1, buff4_1, 10);
	if (-1 == ret) {
		perror ("read value_key1 file error");
		exit (-1);
	}

	//当key1中断发生时, 唤醒poll进程读取value的值
	gpio_value_fd4_3 = open (buff4_3, O_RDONLY);
	if (gpio_value_fd4_3 == -1) {
		perror ("open value_key2 file error");
		exit (-1);
	}
	fds4_3[0].fd = gpio_value_fd4_3;
	fds4_3[0].events = POLLPRI;
	ret = read (gpio_value_fd4_3, buff4_3, 10);
	if (-1 == ret) {
		perror ("read value_key2 file error");
		exit (-1);
	}
	while (1) {
		//监听key1和key2
		if ((ret = poll(fds4_1, 1, 0))) {
			if (fds4_1[0].revents & POLLPRI) {
				ret = lseek (gpio_value_fd4_1, 0, SEEK_SET);
				if (-1 == ret) {
					perror ("lseek error");
				}
				memset (buff4_1, 0, sizeof(BUFFSIZE)/sizeof(char));
				ret = read (gpio_value_fd4_1, buff4_1, 10);
				if (-1 == ret) {
					perror ("read error!");
				}
				printf ("press key1\n");
				//舵机正处于开启状态
				if (steer_statu == 1 && key3 < 2) {
					//关闭舵机
					steer_0degree ();

					steer_statu = 0;
				    	//按键3第key3次被按下
					key3 = key3 + 1;

				} else if (steer_statu == 0 && key3 < 2){
					//关闭自动模式

					//打开舵机
					steer_90degree ();
					steer_statu = 1;
				    //按键3第key3次被按下
					key3 = key3 + 1;
				} else if (key3 == 2) {
					key3 = 0;
				}
				ret = 0;
			}
		}
		if ((ret = poll (fds4_3, 1, 0))) {
			if (fds4_3[0].revents & POLLPRI) {
				ret = lseek (gpio_value_fd4_3, 0, SEEK_SET);
				if (-1 == ret) {
					perror ("lseek error");
				}
				memset (buff4_3, 0, sizeof(BUFFSIZE)/sizeof(char));
				ret = read (gpio_value_fd4_3, buff4_3, 10);
				if (-1 == ret) {
					perror ("read error!");
				}
				printf ("press key2\n");
				//步进电机机正处于开启状态
				if (motor_statu == 1 && key1 < 2) {
					//关闭电机
					for (int i = 0; i < 100; i++) {
						//打开步进电机（关幕布）
						motor_l();
					}

					motor_statu = 0;
				   	//按键1第key1次被按下
					key1 = key1 + 1;

				} else if (motor_statu == 0 && key1 < 2){
					//关闭自动模式

					//打开电机机
					for (int i = 0; i < 100; i++) {
					//打开步进电机（开幕布）
						motor_r();
					}
					motor_statu = 1;
				    //按键1第key1次被按下
					key1 = key1 + 1;
				} else if (key1 == 2) {
					key1 = 0;
				}
				ret = 0;
			}
		}
	}
}

//
//ad：1表示温度，2表示光照值

int main (int argc, char **argv)
{
	unsigned char data, dataa;
	float val, vall;
	int nbytes = 0;
	int nbytess = 0;
	if (argc < 4) {
		printf ("usage: ./app_pcf8591 /dev/pcf8591 0 3\n");
		return -1;
	}
	
	int fd = open (argv[1], O_RDWR);
	if (fd < 0) {
		perror ("app open error!\n ");
		return -1;
	}

	step = (int)((duty2 - duty1) / 10);//1000
	//gpio初始化
	gpio_init ();
	//使能pwm控制器
	PWM_gpio_mode (PWM_ENABLE_REG, WRITE_TYPE_H, PWM_ENABLE_VAL);
	//配置gpio管脚的模式
	PWM_gpio_mode (GPIO_PAD_MOOE_PWM0_CHANNEL0_REG, WRITE_TYPE_H, GPIO_PAD_MOOE_PWM0_CHANNEL0_VAL);
	PWM_gpio_mode (GPIO_PAD_MOOE_PWM2_CHANNEL0_REG, WRITE_TYPE_H, GPIO_PAD_MOOE_PWM2_CHANNEL0_VAL);
	
	//超声波
	config_gpio (4, 4, buff4_4);
	config_gpio (4, 5, buff4_5);
	//步进电机
	config_gpio (4, 11, buff4_11);
	config_gpio (5, 12, buff5_12);
	config_gpio (5, 13, buff5_13);
	config_gpio (5, 14, buff5_14);
	//按键
	config_gpio (4, 1, buff4_1);
	config_gpio (4, 3, buff4_3);

	//将pwm0和pwm2的节点文件导出到用户空间
	//注意这个函数应当在pwm_config()和set_pwm_value()前调用!!!!!
	set_pwm_export ();
	//配置pwm period,duty_cycle,enable
	set_pwm_value ();
	
	rgb_init ();
	
	//舵机初始化
	uart_init();

	//线程负责监测标准输入是否有输入，如果有就终止程序
	pthread_create (&pt_key, NULL, key_func, NULL);
	usleep (10000);
	
	
	while(1) {
/*************************************获取温度或者光照值**************************************************/
/**********************************3表示温度，0表示光照值*************************************************/
		
/*		//使用滑动变阻器模拟温度传感器
		//将命令行参数转换为整型
		fd = open (argv[1], O_RDWR);
		data = (unsigned char)atoi(argv[3]);
		nbytes = read (fd, &data, 1);
		nbytes = write (fd, &data, 1);
		
		val = (float)data * (3.3/255);
		float temp_val = 100 - val*30.3;
		temp_value = (int)temp_val;
		printf ("temp_value = %d\n", temp_value);
		usleep (2000000);
		close (fd);
*/		
		//获取光照值
		//将命令行参数转换为整型
		dataa = (unsigned char)atoi(argv[2]);
		nbytess = read (fd, &dataa, 1);
		nbytess = write (fd, &dataa, 1);
			
		vall = (float)dataa * (3.3/255);
		printf("vall = %.2f\n", vall);

		float temp_val = 100 - (vall-0.87)*42;
		temp_value = (int)temp_val;
		printf ("temp_value = %d\n", temp_value);

		float light_intensity = 200 - (vall-0.87)*85;
		light_value = (int)light_intensity;
		printf ("light_value = %d\n", light_value);
	
		usleep (200000);

/****************************************************************************************/	
		send_ultrasonic ();
		//rgb_init ();
		printf("test1\n");
		distance = get_diatance_value ();
		printf ("distance = %d\n", distance);
		
		if (key3 == 8) {
			if (temp_value > 20) {
				//打开舵机90度（开门窗）
				steer_90degree();
				steer_statu = 1;
				printf("open steer\n");
			}
			if (temp_value <= 10 ) {
				//关闭舵机0度（关门窗）
				steer_0degree();
				steer_statu = 0;
				printf("close steer\n");
			}
		}
		if (key1 == 8) {
			if (light_value >= 40 && motor_statu == 0) {
			printf("open motor\n");
				for (int i = 0; i < 100; i++) {
					//打开步进电机（开幕布）
					motor_r();
				}	
				motor_statu = 1;
			}
			if (light_value < 40 && motor_statu == 1) {
				printf("close motor\n");
				for (int i = 0; i < 100; i++) {
					//打开步进电机（关幕布）
					motor_l();
				}
				motor_statu = 0;
			}
		}
		if (light_value < 50 && distance <= 10) {
			//打开LED
			printf("open LED\n");		
			red_blue_mode ();
		}
		if (light_value  > 50 || distance > 10) {
			//关闭LED
			breath_mode ();
			printf("close LED\n");
			//rgb_init ();
		}
	}
	close (fd);
	system ("rmmod i2c_pcf8591");
	//线程的会合（收尸）
	pthread_join (pt_key, NULL);
	return 0;
}
